<?php

/**
 * 商标管理系统 v1.0.1
 *
 * 商业运营到ubtm.cn官网进行授权使用。
 *
 * (c) cighsen02 <xiayu@959602.com>
 *
 * Create at：2025.07.03
*/

namespace App\Services\Auth;

use App\Models\User;
use Exception;
use Laravel\Passport\RefreshTokenRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

/**
 * 前台访客服务层
 */
class Guest extends UserService
{
    public function __construct(
        protected RefreshTokenRepository $refreshTokenRepository
    )
    {}

    /**
     * 注册用户
     *
     * @param array $add
     * @param string $role
     * @return User
     */
    public function register(array $add, string $role = 'member'): User
    {
        $add['password'] = Hash::make($add['password']);

        return $this->store($add, $role);
    }

    /**
     * 登陆
     *
     * @param array $data
     * @return array
     */
    public function login(array $data): array
    {
        $user = $this->findUserByEmail($data['email']);

        if (empty($user) || !Hash::check($data['password'], $user?->password)) {

            throw new Exception('Invalid credentials');
        }

        return [
            'access_token' => $user->createToken('auth_token')->accessToken,
            'token_type' => 'Bearer'
        ];
    }

    /**
     * 登出
     *
     * @return void
     *
     * @throws Exception
     */
    public function destroy(): void
    {
        if (null === $token = Auth::user()?->token()) {
            throw new Exception('', 404);
        }

        $token->revoke();

        $this->refreshTokenRepository->revokeRefreshTokensByAccessTokenId($token->id);
    }
}
